document.addEventListener('DOMContentLoaded', () => {
    const resetForm = document.getElementById('resetForm');
    const errorMessage = document.getElementById('errorMessage');
    const newPasswordInput = document.getElementById('new_password');
    const confirmPasswordInput = document.getElementById('confirm_password');
    const strengthText = document.getElementById('strengthText');
    const strengthProgress = document.querySelector('.strength-progress');

    // 密码显示/隐藏切换
    setupPasswordToggle();

    // 密码强度检测
    newPasswordInput.addEventListener('input', () => {
        const password = newPasswordInput.value;
        const strength = checkPasswordStrength(password);

        // 更新UI
        strengthText.textContent = strength.text;
        strengthProgress.className = 'strength-progress ' + strength.class;
        strengthProgress.style.width = strength.width;
    });

    // 密码强度检测函数
    function checkPasswordStrength(password) {
        let score = 0;

        // 长度至少8位
        if (password.length >= 8) score++;
        // 包含小写字母
        if (/[a-z]/.test(password)) score++;
        // 包含大写字母
        if (/[A-Z]/.test(password)) score++;
        // 包含数字
        if (/[0-9]/.test(password)) score++;
        // 包含特殊字符
        if (/[^a-zA-Z0-9]/.test(password)) score++;

        // 根据分数返回结果
        if (score <= 2) {
            return { text: '弱', class: 'strength-weak', width: '33%' };
        } else if (score <= 4) {
            return { text: '中', class: 'strength-medium', width: '66%' };
        } else {
            return { text: '强', class: 'strength-strong', width: '100%' };
        }
    }

    // 表单提交事件
    resetForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const newPassword = newPasswordInput.value;
        const confirmPassword = confirmPasswordInput.value;
        const token = new URLSearchParams(window.location.search).get('token');

        // 验证输入
        if (!newPassword || !confirmPassword) {
            showError('请填写所有必填项');
            return;
        }

        if (newPassword !== confirmPassword) {
            showError('两次输入的密码不一致');
            return;
        }

        if (newPassword.length < 8) {
            showError('密码长度至少为8位');
            return;
        }

        try {
            // 发送重置密码请求
            const response = await fetch('/reset_password_process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    new_password: newPassword,
                    token: token
                })
            });

            const result = await response.json();

            if (response.ok) {
                if (result.success) {
                    // 重置成功，跳转到登录页面
                    window.location.href = '/login';
                } else {
                    showError(result.message || '密码重置失败');
                }
            } else {
                showError(result.message || '服务器错误');
            }
        } catch (error) {
            console.error('密码重置失败:', error);
            showError('网络错误，请稍后再试');
        }
    });

    // 显示错误信息
    function showError(msg) {
        errorMessage.textContent = msg;
        resetForm.classList.add('shake');
        setTimeout(() => resetForm.classList.remove('shake'), 500);
    }

    // 获取Cookie
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
});

// 密码显示/隐藏切换函数
function setupPasswordToggle() {
    const togglePassword = document.querySelectorAll('.toggle-password');

    togglePassword.forEach(icon => {
        icon.addEventListener('click', function() {
            const input = this.parentElement.querySelector('input');
            const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
            input.setAttribute('type', type);
            this.classList.toggle('fa-eye-slash');
        });
    });
}